package com.qa.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qa.pojo.PersonHeaderLbtBean;
import com.qa.pojo.Temp_WqtWeb;
import com.qa.pojo.Temp_lbt;
import com.qa.pojo.Temp_user_use;
import com.qa.pojo.Temp_zzttWeb;
import com.qa.pojo.Users;
import com.qa.service.IUserService;
import com.qa.util.GetPostUtil;
import com.qa.util.JsonFormatTool;
import com.qa.util.ShowHttpHeaders;

@Controller
@RequestMapping("/ask")
public class AskController {
	@Resource
	private IUserService userService;
	HisController hisController = new HisController();
	JsonFormatTool jsonFormatTool = new JsonFormatTool();
	String headerKey = null, headerVal = null;
	Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 普通的get和post请求
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/askAndRes")
	@ResponseBody
	public Map<String, Object> askAndResponse(HttpServletRequest request,
			HttpServletResponse response) {

		String resultString = "";
		String params = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		String urlStr;
		try {
			urlStr = URLDecoder.decode(request.getParameter("urlStr"), "utf-8")
					.trim();
			String methodStr = URLDecoder.decode(
					request.getParameter("methodStr"), "utf-8");
			String mapString = request.getParameter("paramsMap");
			Object succesResponse = JSON.parse(mapString); // 先转换成Object
			Map<?, ?> map = (Map<?, ?>) succesResponse; // Object强转换为Map
			Set<?> set = map.keySet();
			Iterator<?> iter = set.iterator();
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			getHeader(usersid);
			if (methodStr.equals("get")) {
				if (map.size() > 0) {
					urlStr = urlStr + "?";
					while (iter.hasNext()) {
						String key = (String) iter.next();
						urlStr += (key.trim() + "=" + map.get(key) + "&");
					}
					urlStr = urlStr.substring(0, urlStr.length() - 1);
				}
				resultString = GetPostUtil
						.sendGet(urlStr, headerKey, headerVal);
				if (resultString == null) {
					resultMap.put("tag", "error");
				} else {
					// 格式化json字符串，便于观看
					resultString = jsonFormatTool.formatJson(resultString);
					// resultString = resultString.replace("\n ", " <br /> ");
					resultMap.put("tag", "success");
					resultMap.put("result", resultString);
					// 插入操作日志
					GetPostUtil.sendPost1(
							"http://localhost:8080" + request.getContextPath()
									+ "/his/insertHis.do",
							"Methodtype=" + methodStr + "&urlStr="
									+ URLEncoder.encode(urlStr, "UTF-8")
									+ "&usersid=" + usersid + "&result="
									+ URLEncoder.encode(resultString, "UTF-8")
									+ "&params="
									+ URLEncoder.encode(params, "UTF-8"));
				}
			} else {
				if (map.size() > 0) {
					while (iter.hasNext()) {
						String key = (String) iter.next();
						params += (key.trim() + "=" + map.get(key) + "&");
					}
					params = params.substring(0, params.length() - 1);
				}
				resultString = GetPostUtil.sendPost(urlStr, params, headerKey,
						headerVal);

				if (resultString == null) {
					resultMap.put("tag", "error");
				} else {
					// 格式化json字符串，便于观看
					resultString = jsonFormatTool.formatJson(resultString);
					// resultString = resultString.replace("\n ", " <br /> ");
					resultMap.put("tag", "success");
					resultMap.put("result", resultString);
					// 插入操作日志
					GetPostUtil.sendPost1(
							"http://localhost:8080" + request.getContextPath()
									+ "/his/insertHis.do",
							"Methodtype=" + methodStr + "&urlStr="
									+ URLEncoder.encode(urlStr, "UTF-8")
									+ "&usersid=" + usersid + "&result="
									+ URLEncoder.encode(resultString, "UTF-8")
									+ "&params="
									+ URLEncoder.encode(params, "UTF-8"));
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * json请求
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/askForJson")
	@ResponseBody
	public Map<String, Object> askForJson(HttpServletRequest request,
			HttpServletResponse response) {
		String resultString = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			String urlStr = URLDecoder.decode(request.getParameter("urlStr"),
					"utf-8").trim();// 通过参数名称接收从前台传来的数据
			String mapString = request.getParameter("paramsMap");
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			getHeader(usersid);
			Object succesResponse = JSON.parse(mapString); // 先转换成Object
			Map<?, ?> map = (Map<?, ?>) succesResponse; // Object强转换为Map
			Set<?> set = map.keySet();
			Iterator<?> iter = set.iterator();
			JSONObject jsobj2 = new JSONObject();

			if (map.size() > 0) {
				while (iter.hasNext()) {
					String key = (String) iter.next();
					jsobj2.put(key.trim(), map.get(key));
				}
			}
			resultString = GetPostUtil.post(urlStr, jsobj2, headerKey,
					headerVal);
			if (resultString == null || resultString == "") {
				resultMap.put("tag", "error");
			} else {
				// 格式化json字符串，便于观看
				resultString = jsonFormatTool.formatJson(resultString);
				// resultString = resultString.replace("\n ", " <br /> ");
				resultMap.put("tag", "success");
				resultMap.put("result", resultString);
				// 插入操作日志
				GetPostUtil.sendPost1(
						"http://localhost:8080" + request.getContextPath()
								+ "/his/insertHis.do",
						"Methodtype=post&urlStr="
								+ URLEncoder.encode(urlStr, "UTF-8")
								+ "&usersid=" + usersid + "&result="
								+ URLEncoder.encode(resultString, "UTF-8")
								+ "&params="
								+ URLEncoder.encode(mapString, "UTF-8"));
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 方法名称:transStringToMap 传入参数:mapString 形如 username'chenziwen^password'1234
	 * 返回值:Map
	 */
	public Map<String, String> transStringToMap(String mapString) {
		Map<String, String> map = new HashMap<String, String>();
		java.util.StringTokenizer items;
		for (StringTokenizer entrys = new StringTokenizer(mapString, ","); entrys
				.hasMoreTokens(); map.put(items.nextToken(), (String) (items
				.hasMoreTokens() ? ((Object) (items.nextToken())) : null)))
			items = new StringTokenizer(entrys.nextToken(), ":");
		return map;
	}

	/**
	 * 根据登录用户获取当前用户的header配置
	 * 
	 * @param usersid
	 */
	public void getHeader(int usersid) {
		// 先获取个人header配置里面的唯一值，通过projename判断是那个项目，
		// 然后根据项目找指定的表获取对应的header配置，再根据配置去获取token等
		PersonHeaderLbtBean lbtBean = null;
		Temp_user_use perHeaderType = userService.getPerHeaderType(usersid);
		if (perHeaderType != null) {
			// 如果是lbt项目的header
			if (perHeaderType.getProjectname().equals("lbt")) {
				Temp_lbt temp_lbt = userService.getPerHeader(
						perHeaderType.getTempid()).get(0);
				if (temp_lbt != null) {
					lbtBean = new PersonHeaderLbtBean();
					lbtBean.setUsersid(perHeaderType.getUsersid());
					lbtBean.setProjectname(perHeaderType.getProjectname());
					lbtBean.setTempid(perHeaderType.getTempid());
					lbtBean.setAppver(temp_lbt.getAppver());
					lbtBean.setImsi(temp_lbt.getImsi());
					lbtBean.setLoginname(temp_lbt.getLoginname());
					lbtBean.setPassword(temp_lbt.getPassword());
					lbtBean.setPhonemodel(temp_lbt.getPhonemodel());
					lbtBean.setPlatform(temp_lbt.getPlatform());
					lbtBean.setSysver(temp_lbt.getSysver());
					lbtBean.setUrl(temp_lbt.getUrl());

					String aString = GetPostUtil.sendPost1(
							lbtBean.getUrl(),
							"platform=" + lbtBean.getPlatform() + "&loginName="
									+ lbtBean.getLoginname() + "&sysver="
									+ lbtBean.getSysver() + "&phonemodel="
									+ lbtBean.getPhonemodel() + "&passWord="
									+ lbtBean.getPassword() + "&appver="
									+ lbtBean.getAppver() + "&imsi="
									+ lbtBean.getImsi());
					String[] getTokenList = aString.split(",");
					String token = null, t_schoolid = null, s_schoolid = null, t_teacherid = null, s_parentid = null;
					for (String a : getTokenList) {
						if (a.contains("token")) {
							String[] getToken = a.split(":");
							if (getToken.length > 0 && getToken[1] != null
									&& !getToken[1].equals("null")) {
								token = getToken[1].substring(1,
										getToken[1].length() - 1);
							}
						}
						if (a.contains("parent")) {
							String[] getparentid = a.split(":");
							if (getparentid.length > 0
									&& getparentid[2] != null
									&& !getparentid[2].equals("null")) {
								s_parentid = getparentid[2];
							}
						}
						if (a.contains("schoolID")) {
							String[] getSchoolid = a.split(":");
							if (getSchoolid.length > 0
									&& getSchoolid[1] != null
									&& !getSchoolid[1].equals("null")) {
								s_schoolid = getSchoolid[1];
							}
						}
						if (a.contains("iSchoolId")) {
							String[] getSchoolid = a.split(":");
							if (getSchoolid.length > 0
									&& getSchoolid[1] != null
									&& !getSchoolid[1].equals("null")) {
								t_schoolid = getSchoolid[1];
							}
						}
						if (a.contains("iTeacherId")) {
							String[] getSchoolid = a.split(":");
							if (getSchoolid.length > 2
									&& getSchoolid[2] != null
									&& !getSchoolid[2].equals("null")) {
								t_teacherid = getSchoolid[2];
							}
						}
					}
					// 如果老师的信息都获取到且家长的都没获取到，认为当前是老师
					if (token != null && t_schoolid != null
							&& t_teacherid != null && s_parentid == null
							&& s_schoolid == null) {
						headerKey = "token";
						headerVal = "sys_token=" + token + "&sys_id="
								+ t_schoolid + "_" + t_teacherid + "_1";
					} else if (token != null && t_schoolid == null
							&& t_teacherid == null && s_parentid != null
							&& s_schoolid != null) {
						// 如果家长都获取到，老师都没获取到，认为是家长
						headerKey = "token";
						headerVal = "sys_token=" + token + "&sys_id="
								+ s_schoolid + "_" + s_parentid + "_3";
					} else {
						System.out.println("token获取异常或者无法判断老师家长");
					}
					System.out.println("==token==" + token + "==t_schoolid=="
							+ t_schoolid + "==t_teacherid==" + t_teacherid
							+ "==s_parentid==" + s_parentid + "==s_schoolid=="
							+ s_schoolid);
				}
			} else if (perHeaderType.getProjectname().equals("wqtweb")) {
				Temp_WqtWeb temp_WqtWeb = userService
						.getWqtWebHeader(perHeaderType.getTempid());
				ArrayList<String> websites = new ArrayList<String>();
				String url = temp_WqtWeb.getUrl() + "?" + "userName="
						+ temp_WqtWeb.getUserName() + "&userPassword="
						+ temp_WqtWeb.getUserPassword() + "&v_qy_Num="
						+ temp_WqtWeb.getV_qy_Num();
				// websites.add("http://szwq.ultradp.com/szwq/loginaction/loginTag.htm?userName=15093131283&userPassword=yangdawei&v_qy_Num=");
				websites.add(url);
				ShowHttpHeaders showHttpHeaders = new ShowHttpHeaders(websites);
				String getCookieValue = showHttpHeaders.getHeaders();
				if (getCookieValue != null) {
					headerKey = "cookie";
					headerVal = getCookieValue.substring(1,
							getCookieValue.length() - 1);
				}
			} else if (perHeaderType.getProjectname().equals("zzttweb")) {
				Temp_zzttWeb temp_zzttWeb = userService
						.getZzttWebHeader(perHeaderType.getTempid());
				ArrayList<String> websites = new ArrayList<String>();
				String url = temp_zzttWeb.getUrl() + "?" + "userName="
						+ temp_zzttWeb.getUsername() + "&password="
						+ temp_zzttWeb.getPassword() + "&enamesubcomp="
						+ temp_zzttWeb.getEnamesubcomp();
				// websites.add("http://szwq.ultradp.com/szwq/loginaction/loginTag.htm?userName=15093131283&userPassword=yangdawei&v_qy_Num=");
				websites.add(url);
				ShowHttpHeaders showHttpHeaders = new ShowHttpHeaders(websites);
				String getCookieValue = showHttpHeaders.getHeaders();
				if (getCookieValue != null) {
					headerKey = "cookie";
					headerVal = getCookieValue.substring(1,
							getCookieValue.length() - 1);
				}
			}
		}
	}
}